package com.example.bookshop.controller;

import com.example.bookshop.VO.CartItemVO;
import com.example.bookshop.service.CartService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.math.BigDecimal;
import java.security.Principal;
import java.util.List;

/**
 * @auth shanyue
 * @date 2025年06月04日16:10
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Resource
    private CartService cartService;

    @GetMapping
    public String viewCart(Model model, Principal principal) {
        String username = principal.getName();
        List<CartItemVO> cartItems = cartService.getCartItems(username);
        BigDecimal totalPrice = cartService.getTotalPrice(username);

        model.addAttribute("cartItems", cartItems);
        model.addAttribute("totalPrice", totalPrice);

        return "cart";
    }

    @PostMapping("/add")
    public String addToCart(@RequestParam int bookId,
                            @RequestParam int quantity,
                            Principal principal,
                            RedirectAttributes redirectAttributes) {
        String msg = cartService.addToCart(bookId, quantity, principal.getName());
        redirectAttributes.addFlashAttribute("msg", msg);
        return "redirect:/";
    }

    @PostMapping("/remove")
    public String removeFromCart(@RequestParam int cartId,
                                 Principal principal,
                                 RedirectAttributes redirectAttributes) {
        String msg = cartService.removeFromCart(cartId, principal.getName());
        redirectAttributes.addFlashAttribute("msg", msg);
        return "redirect:/cart";
    }
}
